package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.DataFormatException;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }




    /*
        新增菜品
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //菜品要插入，口味要插入
        //DTO数据要转换为Entity数据
        Dish dish = new Dish();
        dish.setStatus(StatusConstant.DISABLE);  //默认停售
        BeanUtils.copyProperties(dishDTO, dish);
        //插入到dish中
        dishMapper.insert(dish); //TODO:让主键回显

        //口味
        //因为菜品表和口味表是一对多关系，口味表是从表插入数据需要菜品表得ID
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断flavors是否有数据
        if (flavors != null && flavors.size() > 0) {
            //遍历：将dishID给到flavor
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            //访问DishFlavorMapper插入数据
            dishFlavorMapper.insertBach(flavors);
        }
    }

    //菜品分页查询
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //分页插件或者页码和数据
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    //批量删除菜品
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {

        //遍历集合，拿出每个id
        ids.forEach(id -> {
            Dish dish = dishMapper.getById(id);
            //判断菜品有没有起售中得商品，如果有不能删除
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //中断逻辑，抛出异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //判断菜品是否存在于套餐中，如果有不能删
        //找到存在菜品的套餐id
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishId(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //抛出异常，中断逻辑
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品，并且删除菜品对应得口味
        ids.forEach(id -> {
            dishMapper.deleteById(id);  //删除菜品
            dishFlavorMapper.deleteByDishId(id); //删除口味
        });
    }

    //根据id查询数据
    @Override
    public DishVO getById(Long id) {

        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);

        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        //将查询到的数据封装到VO中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //修改菜品表基本信息
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBach(flavors);
        }
    }

    //根据分类id查询菜品
    @Override
    @Transactional
    public List<Dish> getCategoryId(Long categoryId) {
        List<Dish> dishes = dishMapper.getCategoryId(categoryId);
        return dishes;
    }
}
